<template>
  <div class="district-container">
    <a-button type="primary" class="add-district-manager" @click="handleAddDistrict">添加片区</a-button>
    <a-table :columns="columns" :data-source="districtData" :loading="isLoading" bordered>
      <template
        v-for="col in ['district', 'address']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="record.editable && col==='district'">
            <a-select style="margin: -5px 0" :default-value="text"
                      @change="handleSelectChange">
              <a-select-option value="华中片区">华中片区</a-select-option>
              <a-select-option value="华北片区">华北片区</a-select-option>
              <a-select-option value="华东片区">华东片区</a-select-option>
              <a-select-option value="东北片区">东北片区</a-select-option>
              <a-select-option value="西北片区">西北片区</a-select-option>
              <a-select-option value="深圳分公司">深圳分公司</a-select-option>
              <a-select-option value="宁波分公司">宁波分公司</a-select-option>
              <a-select-option value="重庆分公司">重庆分公司</a-select-option>
              <a-select-option value="沈阳分公司">沈阳分公司</a-select-option>
              <a-select-option value="云南分公司">云南分公司</a-select-option>
              <a-select-option value="泉州分公司">泉州分公司</a-select-option>
            </a-select>
          </template>
          <template>
            <a-input
              v-if="record.editable && (col==='address')"
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
          </template>
          <template  v-if="!record.editable">
            {{ text }}
          </template>
        </div>
      </template>
      <template slot="operate" slot-scope="text, record, index">
        <div class="editable-row-operations">
        <span v-if="record.editable">
          <a-button @click="() => save(record.key)" type="primary" class="district-update">确认修改</a-button>
        </span>
          <span v-else>
          <a-button :disabled="editingKey !== ''" @click="() => edit(record.address, record.key)" type="primary"
                    class="district-update">修改</a-button>
        </span>
          <a-button @click="() => handleDelete(record.district)" type="danger">删除</a-button>
        </div>
      </template>
      <template slot="address" slot-scope="text, record, index">
        <div class="editable-row-operations">
        <span v-if="record.editable">
          <a-input v-model="selectedAddress || record.address" class="address-container-input" readOnly />
          <a-button class="address-container-button" type="primary" @click="handleChoose(record.address)">选择</a-button>
        </span>
          <span v-else>
            <div>{{record.address}}</div>
        </span>
        </div>
      </template>
      <template slot="deleteDistrict" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <a-button @click="() => handleDelete(record.id)" type="danger">删除</a-button>
        </div>
      </template>
    </a-table>
    <a-modal v-model="visible" title="选择区域" okText="确定" cancelText="取消" @ok="handleChooseOk">
      <div class="address-model-container">
        <a-checkbox-group @change="onChange" :default-value="addressArray">
          <a-row>
            <a-col :span="6"><a-checkbox value="北京市">北京市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="天津市">天津市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="上海市">上海市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="重庆市">重庆市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河北省">河北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山西省">山西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="内蒙古">内蒙古</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="辽宁省">辽宁省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="吉林省">吉林省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="黑龙江省">黑龙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江苏省">江苏省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="浙江省">浙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="安徽省">安徽省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="福建省">福建省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江西省">江西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山东省">山东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河南省">河南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖北省">湖北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖南省">湖南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广东省">广东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广西">广西</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="海南省">海南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="四川省">四川省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="贵州省">贵州省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="云南省">云南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="西藏">西藏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="陕西省">陕西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="甘肃省">甘肃省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="青海省">青海省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="宁夏">宁夏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="新疆">新疆</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="香港">香港</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="澳门">澳门</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="台湾省">台湾省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="研究院">研究院</a-checkbox></a-col>
          </a-row>
        </a-checkbox-group>
      </div>
    </a-modal>

    <a-modal v-model="addDistrictVisible" title="添加片区" okText="确定" cancelText="取消"
             @ok="handleAddDistrictOk" @cancel="handleAddDistrictCancel">
      <div class="add-model-container">
        <a-form :form="form">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="所属片区"
          >
            <a-select style="margin: -5px 0" @change="handleAddSelectChange"
                      v-decorator="['district',
                        { initialValue: addSelectValue,
                          rules: [{ required: true, message: '' }] },
                      ]">
              <a-select-option value="华中片区">华中片区</a-select-option>
              <a-select-option value="华东片区">华东片区</a-select-option>
              <a-select-option value="东北片区">东北片区</a-select-option>
              <a-select-option value="西北片区">西北片区</a-select-option>
              <a-select-option value="深圳分公司">深圳分公司</a-select-option>
              <a-select-option value="宁波分公司">宁波分公司</a-select-option>
              <a-select-option value="重庆分公司">重庆分公司</a-select-option>
              <a-select-option value="沈阳分公司">沈阳分公司</a-select-option>
              <a-select-option value="云南分公司">云南分公司</a-select-option>
              <a-select-option value="泉州分公司">泉州分公司</a-select-option>
              <a-select-option value="滕州分公司">滕州分公司</a-select-option>
            </a-select>
          </a-form-item>
          <!--<a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="选择省、市"
          >
            <a-input
              v-decorator="[
          'username',
          { rules: [{ required: true, message: '请输入有效的电话号码', pattern: /^1[3|4|5|7|8][0-9]\d{8}$/ }] },
        ]"
              placeholder="请选择省、市"
            />
          </a-form-item>-->

          <a-form-item
            :label-col="buttonFormItemLayout.labelCol"
            :wrapper-col="buttonFormItemLayout.wrapperCol"
            label="选 择 省"
          >
            <a-input  class="add-district-input" placeholder="" v-model="dispatchAddress" readOnly />
            <a-button type="primary" class="add-district-button" @click="showDistrictToast">选择</a-button>
          </a-form-item>

        </a-form>
      </div>
    </a-modal>

    <a-modal v-model="addDistrictToastVisible" title="选择片区" okText="确定" cancelText="取消" @ok="handleChooseToastOk">
      <div class="address-model-container">
        <a-checkbox-group @change="onChangeToast">
          <a-row>
            <a-col :span="6"><a-checkbox value="北京市">北京市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="天津市">天津市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="上海市">上海市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="重庆市">重庆市</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河北省">河北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山西省">山西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="内蒙古">内蒙古</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="辽宁省">辽宁省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="吉林省">吉林省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="黑龙江省">黑龙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江苏省">江苏省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="浙江省">浙江省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="安徽省">安徽省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="福建省">福建省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="江西省">江西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="山东省">山东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="河南省">河南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖北省">湖北省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="湖南省">湖南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广东省">广东省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="广西">广西</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="海南省">海南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="四川省">四川省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="贵州省">贵州省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="云南省">云南省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="西藏">西藏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="陕西省">陕西省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="甘肃省">甘肃省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="青海省">青海省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="宁夏">宁夏</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="新疆">新疆</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="香港">香港</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="澳门">澳门</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="台湾省">台湾省</a-checkbox></a-col>
            <a-col :span="6"><a-checkbox value="研究院">研究院</a-checkbox></a-col>
          </a-row>
        </a-checkbox-group>
      </div>
    </a-modal>
  </div>
</template>

<script>
  const columns = [
    {
      title: '序号',
      dataIndex: 'sequence',
      key: 'sequence',
      width: '8%',
      scopedSlots: { customRender: 'sequence' },
    }, {
      title: '所属片区',
      dataIndex: 'district',
      key: 'district',
      width: '15%',
      scopedSlots: { customRender: 'district' },
    }, {
      title: '所在省份',
      dataIndex: 'address',
      key: 'address',
      width: '25%',
      scopedSlots: { customRender: 'address' },
    }, {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      width: '10%',
      scopedSlots: { customRender: 'operate' },
    }
  ];
  const formItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
  };
  const dispatchFormItemLayout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 10 },
  };
  const buttonFormItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
  };
  import GLOBAL from '@/api/global_variable'
  import api from '@/server/userConfig';
  export default {
    name: 'DistrictTable',
    components: {
    },
    props: {
      userName: String
    },
    data () {
      return {
        districtData: [],
        addSelectValue: '华中片区',
        columns,
        editingKey: '',
        isLoading: false,
        visible: false,
        addDistrictVisible: false,
        addDistrictToastVisible: false,
        cacheData: [],
        selectedAddress: '',
        addressArray: [],
        dispatchAddress: '',
        toastSelectedAddress: '',
        formItemLayout,
        buttonFormItemLayout,
        dispatchFormItemLayout,
        serviceList: [],
        managerUsername: '',
        count: 0,
        form: this.$form.createForm(this, { name: 'dynamic_rule' }),
        dispatchForm: this.$form.createForm(this, { name: 'dispatch_form' }),
        compId: -1,
      }
    },
    mounted () {
      this.getDistrictList();
    },
    methods: {
      handleSelectChange (value) {
        console.log(value);
      },
      handleAddSelectChange (value) {
        this.addSelectValue = value;
      },
      // 点击删除;
      handleDelete (district) {
        this.$Modal.confirm({
          title: '确认删除此片区吗?',
          content: '',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: async () => {
            const res = await api.deleteDeployDistrict({compId: this.compId, district});
            console.log(res);
            if (res.MsgCode === 0) {
              this.$message.success('删除成功');
              // 前端删除此行;
              const dataSource = [...this.districtData];
              this.districtData = dataSource.filter(item => item.district !== district);
            }
          },
          onCancel() {}
        })
      },
      // 增加片区;
      handleAddDistrict () {
        this.addDistrictVisible = true;
      },
      // 点击添加片区的取消;
      handleAddDistrictCancel () {
        this.form.resetFields();
      },
      // 点击添加片区的确定;
      handleAddDistrictOk () {
        this.form.validateFields((err, values) => {
          if (!err) {
            //console.log(values);
            //console.log(this.toastSelectedAddress);
            if (this.toastSelectedAddress === "") {
              this.$message.warning('省份不能为空');
              return;
            }
            this.addDistrictVisible = false;
            // 发送ajax请求;
            this.handleAddDistrictPerson(values.district, this.toastSelectedAddress);
            this.form.resetFields();
          }
        });
      },
      async handleAddDistrictPerson (district, address) {
        let areaManagerData = {};
        areaManagerData.compId = this.compId;
        areaManagerData.district = district;
        areaManagerData.address = address;
        const res = await api.reqAddDeployList({
          compId: areaManagerData.compId,
          district: areaManagerData.district,
          province: areaManagerData.address
        });
        if (res.MsgCode === 0) {
          this.$message.success('添加成功');
          setTimeout(() => {
            window.location.reload();
          }, 400);
          // this.toastSelectedAddress = '';
          // this.dispatchAddress = '';
          // this.form.resetFields();
          // this.getDistrictList();
        }
      },
      // 点击增加片区主管的选择按钮;
      showDistrictToast () {
        this.addDistrictToastVisible = true;
      },
      // 点击选择
      handleChoose (address) {
        this.visible = true;
        this.addressArray = address.split(',');
      },
      handleChooseOk () {
        console.log(this.selectedAddress);
        this.visible = false;
      },
      onChange (checkedValues) {
        this.selectedAddress = checkedValues.join(',');
        //console.log('checked = ', checkedValues);
        console.log(this.selectedAddress);
      },
      // 点击添加片区主管的选择的每一项;
      onChangeToast (toastCheckedValues) {
        this.toastSelectedAddress = toastCheckedValues.join(',');
        //console.log(this.toastSelectedAddress);
      },
      handleChooseToastOk () {
        this.dispatchAddress = this.toastSelectedAddress;
        this.addDistrictToastVisible = false;
      },
      async getDistrictList () {
        this.isLoading = true;
        const userData = JSON.parse(localStorage.getItem('userData'));
        this.compId = userData.compid;
        const res =  await api.getDeployList({compId: userData.compid});
        this.isLoading = false;
        if (res.MsgCode !== 0) {
          return;
        }
        let districtData = res.Data;
        const districtDataLength = districtData.length;
        for (let i = 0; i < districtDataLength; i++){
          districtData[i].sequence = i + 1;
          districtData[i].key = i + 1;
          districtData[i].province = Array.from(new Set(districtData[i].province));
          districtData[i].address = districtData[i].province.join(',');
        }
        //console.log(districtData);
        this.districtData = districtData;
        this.cacheData = this.districtData.map(item => ({ ...item }));
      },

      handleChange (value, key, column) {
        const newData = [...this.districtData];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
          target[column] = value;
          this.districtData = newData;
        }
      },
      edit (address, key) {
        this.addressArray = address.split(',');
        const newData = [...this.districtData];
        const target = newData.filter(item => key === item.key)[0];
        this.editingKey = key;
        if (target) {
          target.editable = true;
          this.districtData = newData;
        }
      },
      async save (key) {
        const newData = [...this.districtData];
        const newCacheData = [...this.cacheData];
        const target = newData.filter(item => key === item.key)[0];
        const updateNewData = {};
        updateNewData.district = target.district;
        updateNewData.address = this.selectedAddress || this.addressArray.join(',');
        updateNewData.compId = this.compId;
        console.log(updateNewData);
        const res = await api.reqUpdateDeployList({
          compId: updateNewData.compId,
          district: updateNewData.district,
          province: updateNewData.address
        });
        console.log(res);
        if (res.MsgCode === 0) {
          // this.$message.success('修改成功!');
          // this.getDistrictList();
          this.$Modal.success({
            title: '',
            content: '修改成功!',
            okText: '确定',
            onOk: () => {
              window.location.reload();
            }
          });
        }
        const targetCache = newCacheData.filter(item => key === item.key)[0];
        if (target && targetCache) {
          delete target.editable;
          this.districtData = newData;
          Object.assign(targetCache, target);
          this.cacheData = newCacheData;
        }
        this.editingKey = '';
      },
      cancel (key) {
        const newData = [...this.districtData];
        const target = newData.filter(item => key === item.key)[0];
        this.editingKey = '';
        if (target) {
          Object.assign(target, this.cacheData.filter(item => key === item.key)[0]);
          delete target.editable;
          this.districtData = newData;
        }
      }
    }
  }
</script>

<style scoped>
  @import './style.css';
</style>
